﻿#pragma execution_character_set("utf-8")
#include <QFileDialog>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDialog>
#include <QToolBar> //工具栏
#include <QStatusBar>
#include <QDockWidget>
#include <QProgressBar>
#include "dialognet.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setAcceptDrops(true);
    ui->graphicsView->setAcceptDrops(false);
    ui->graphicsView->setScene(&scene);

    ui->graphicsView_2->setScene(&scene2);

    ui->graphicsView->setInteractive(true);
    ui->graphicsView->setDragMode(QGraphicsView::RubberBandDrag);
    ui->graphicsView->setRubberBandSelectionMode(Qt::ContainsItemShape);

    ui->graphicsView_2->setInteractive(true);
    ui->graphicsView_2->setDragMode(QGraphicsView::RubberBandDrag);
    ui->graphicsView_2->setRubberBandSelectionMode(Qt::ContainsItemShape);

    ui->horizontalSlider->setRange(0,0);
    ui->label->setText(QString::number(ui->horizontalSlider->value()));


   // this->io = new Ui::IoInterface();
   // this->io->setupUi(this);


    setWindowTitle(tr("目标检出"));
    createActions();
    createMenus();


    fileMenu = menuBar()->addMenu(tr("网络连接"));
    QAction *p1 = fileMenu->addAction(tr("模态对话框"));
    fileMenu->addSeparator();
    QAction *p2 = fileMenu->addAction(tr("非模态对话框"));


    //菜单栏 QMenuBar
    //工具栏 QToolBar

    QToolBar *toolBar = addToolBar("toolBar");
    //工具栏添加快捷键
    toolBar->addAction(p1);
    QPushButton *b = new QPushButton(this);
    b->setText("^_^");
    toolBar->addWidget(b);
    connect(b, &QPushButton::clicked,[=](){
        b->setText("123");
    });

    //状态栏

    QStatusBar * status_bar =  statusBar();
    QLabel *lab_ipaddr = new QLabel(this);
    QLabel *lab_port = new QLabel(this);
    status_bar->addWidget(lab_ipaddr);
    btn_socket_connect = new QPushButton(this);
    btn_socket_connect->setText("连接");
    status_bar->addWidget(btn_socket_connect);
    //addwidge 左往右添加
    status_bar->addWidget(new QLabel("2",this));
    //从右往左
    status_bar->addPermanentWidget(new QLabel("3",this));
//    status_bar->addWidget(new QProgressBar(this));//添加进度条
    //核心控件
    //浮动窗口
    QDockWidget *dock = new QDockWidget(this);
    addDockWidget(Qt::RightDockWidgetArea, dock);
    QTextEdit * textEdit1 = new QTextEdit(this);
    dock->setWidget(textEdit1);

    initSocketCfg();
    lab_ipaddr->setText(ip_addr + " : " + QString::number(port));


    qDebug() <<file_list_[0];

    connect(p1, &QAction::triggered, [=](){
//        QDialog dlg;
        DialogNet dlg;
        dlg.exec();
        qDebug()<<"sss";
    });

    connect(p1, &QAction::triggered, [=](){
        QDialog dlg;
        dlg.show();
        qDebug()<<"sss";
    });

//    subWindow.show();
    // 定时器绘图功能
    connect(&m_Timer,&QTimer::timeout,
            [=](){
            m_IndexFrame++;
            QPixmap pixmap;
            QPixmap pixmap_sum;
            ui->label->setText(QString::number(m_IndexFrame));
            ui->horizontalSlider->setValue(m_IndexFrame);
            qDebug()<<m_filePath;
            if(m_IndexFrame <m_filePath.length())     {
              ui->labFilePath->setText(m_filePath.at(m_IndexFrame));
              if(pixmap.load(m_filePath.at(m_IndexFrame)))
              {
                  QGraphicsPixmapItem* item = new QGraphicsPixmapItem(pixmap);
                  item->setPos(QPointF(0,0));
                  item->setFlag(QGraphicsItem::ItemIsSelectable);
                  item->setAcceptedMouseButtons(Qt::LeftButton);
                  scene.clear();
                  scene.addItem(item);

                  if(m_IndexFrame< m_SumFilePath.length()){
                    pixmap_sum.load(m_SumFilePath.at(m_IndexFrame));
                    QGraphicsPixmapItem* item2 = new QGraphicsPixmapItem(pixmap_sum);
                    item2->setPos(QPointF(0,0));
                    item2->setFlag(QGraphicsItem::ItemIsSelectable);
                    item2->setAcceptedMouseButtons(Qt::LeftButton);
                    scene2.clear();
                    scene2.addItem(item2);
                  }
              }
          }else{
            ui->pushButton->setText("运行");
            m_Timer.stop();
            qDebug()<<m_Timer.isActive();
            m_IndexFrame = 0;
          }


    });


    connect(this, SIGNAL(outDisplay(QPixmap)), this, SLOT(imageShow(QPixmap)));
    //connect(subSocketWnd.async_process_, &AsyncProcess::outDisplay(QPixmap), this, SLOT(imageShow(QPixmap)));

    connect(ui->graphicsView, &QEnhancedGraphicsView::sendZoomFactor,[=](double zoomFactor, QPointF sceneMousePos){
        ui->graphicsView_2->scale(zoomFactor, zoomFactor);
        ui->graphicsView_2->centerOn(sceneMousePos);
    });

    connect(ui->graphicsView_2, &QEnhancedGraphicsView::sendZoomFactor,[=](double zoomFactor, QPointF sceneMousePos){
        ui->graphicsView->scale(zoomFactor, zoomFactor);
        ui->graphicsView->centerOn(sceneMousePos);
    });

}
void MainWindow::on_pushButton_clicked()
{
    //启动定时器
    //时间间隔100ms
    //每隔100ms定时器myTimer自动出发timeout;
    if(m_Timer.isActive() == false){
        m_Timer.start(500) ;
        ui->pushButton->setText("暂停");
    }else{
        m_Timer.stop();
        ui->pushButton->setText("运行");
    }



}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::createActions()
{
    //“打开”动作
    openFileAction = new QAction(QIcon("open.png"), tr("打开文件夹"), this);//(a)
    openFileAction->setShortcut(tr("Ctrl+O"));                    //(b)
    openFileAction->setStatusTip(tr("打开一个文件"));               //(c)
    connect(openFileAction, SIGNAL(triggered()), this, SLOT(showOpenFile()));

}
void MainWindow::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("文件"));
    fileMenu->addAction(openFileAction);				//(b)

}
void MainWindow::closeEvent(QCloseEvent* event)
{
    event->accept();
}
void MainWindow::showOpenFile()
{

    QString path = QFileDialog::getExistingDirectory(NULL, tr("选择文件夹"), "H:/home/htcz/Data", QFileDialog::ShowDirsOnly);

    QDir* dir = new QDir(path);
    dir->setFilter(QDir::Dirs | QDir::Files);
    dir->setSorting(QDir::DirsFirst);//优先显示目录
    if(!dir->cd("reg/tiff")){
        qDebug()<<dir->absolutePath();
        qWarning(dir->absolutePath().toLatin1().data());
        return;
    }
    QStringList filter;
    filter << "*.png" << "*.jpg"<< "*.tiff";
    fileInfo = new QList<QFileInfo>(dir->entryInfoList(filter));
    ui->horizontalSlider->setRange(0,fileInfo->count());
    for (int i = 0; i < fileInfo->count(); i++)
    {
       ui->textBrowser->append(fileInfo->at(i).fileName());
    }

     if(!dir->cd("../../track/tiff")){
        qDebug()<<dir->absolutePath();
        qWarning("无法打开track文件夹");
     }else{
         qDebug()<<dir->absolutePath();
         m_fileInfoSum = new QList<QFileInfo>(dir->entryInfoList(filter));
         for (int i = 0; i < m_fileInfoSum->count(); i++)
         {
            if(m_fileInfoSum->at(i).fileName().contains("tracked")){
                m_SumFilePath.push_back((m_fileInfoSum->at(i).filePath()));
            }
         }
     }
//    qDebug() << fileInfo->count();
//    qDebug() << path;
    //std::cout << std::endl;
    //if(!fileName.isEmpty())
    //{
    //    if(showWidget->text->document()->isEmpty())
    //    {
    //        loadFile(fileName);
    //    }
    //    else
    //    {
    //        ImgProcessor *newImgProcessor =new ImgProcessor;
    //        newImgProcessor->show();
    //        newImgProcessor->loadFile(fileName);
    //    }
    //}
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    QStringList acceptedFileTypes;
    acceptedFileTypes.append("jpg");
    acceptedFileTypes.append("png");
    acceptedFileTypes.append("bmp");
    acceptedFileTypes.append("tif");
    acceptedFileTypes.append("tiff");

    if (event->mimeData()->hasUrls() &&
            event->mimeData()->urls().count() == 1)
    {

        QFileInfo file(event->mimeData()->urls().at(0).toLocalFile());
        if(acceptedFileTypes.contains(file.suffix().toLower()))
        {
            event->acceptProposedAction();
        }
    }
}

void MainWindow::dropEvent(QDropEvent *event)
{
    QPoint viewPos = ui->graphicsView->mapFromParent(event->pos());
    QPointF sceneDropPos = ui->graphicsView->mapToScene(viewPos);

    QFileInfo file(event
                   ->mimeData()
                   ->urls()
                   .at(0)
                   .toLocalFile());
    QPixmap pixmap;
    if(pixmap.load(file
                   .absoluteFilePath()))
    {
        QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap);
        QGraphicsPixmapItem *item2 = new QGraphicsPixmapItem(pixmap);
        item->setPos(sceneDropPos);
        item->setFlag(QGraphicsItem::ItemIsSelectable);
        item->setAcceptedMouseButtons(Qt::LeftButton);
        scene.addItem(item);
        scene2.addItem((item2));
    }
    else
    {
        QMessageBox::critical(this,
                              tr("Error"),
                              tr("The image file cannot be read!"));
    }
}



void MainWindow::on_comboBox_activated(const QString &arg1)
{
    qDebug() << arg1;
  ui->textBrowser->clear();
  m_filePath.clear();
  for (int i = 0; i < fileInfo->count(); i++)
  {
      if (fileInfo->at(i).fileName().contains(ui->comboBox->currentText())) {
          qDebug() << fileInfo->at(i).filePath();
          m_filePath.push_back(fileInfo->at(i).filePath());
          ui->textBrowser->append(fileInfo->at(i).fileName());
      }
  }

}


void MainWindow::on_horizontalSlider_sliderMoved(int position)
{
    qDebug()<<position;
    ui->label->setText(QString::number(ui->horizontalSlider->value()));
    m_IndexFrame = ui->horizontalSlider->value();

    if(m_IndexFrame < m_filePath.length())     {
        QPixmap pixmap;

        pixmap.load(m_filePath.at(m_IndexFrame));
        QGraphicsPixmapItem* item = new QGraphicsPixmapItem(pixmap);
        item->setPos(QPointF(0,0));
        item->setFlag(QGraphicsItem::ItemIsSelectable);
        item->setAcceptedMouseButtons(Qt::LeftButton);
        scene.clear();
        scene.addItem(item);
     }

     if(m_IndexFrame< m_SumFilePath.length()){
        QPixmap pixmap_sum;
        pixmap_sum.load(m_SumFilePath.at(m_IndexFrame));
        QGraphicsPixmapItem* item2 = new QGraphicsPixmapItem(pixmap_sum);
        item2->setPos(QPointF(0,0));
        item2->setFlag(QGraphicsItem::ItemIsSelectable);
        item2->setAcceptedMouseButtons(Qt::LeftButton);
        scene2.clear();
        scene2.addItem(item2);
    }

}
void MainWindow::imageShow(QPixmap image) {

    QPixmap pixmap;
    pixmap.load("H:/home/htcz/Data/202109/17/05/split_00/reg/tiff/flt_src4809.tiff");

    QGraphicsPixmapItem* item = new QGraphicsPixmapItem(image);
    item->setPos(QPointF(0, 0));
    item->setFlag(QGraphicsItem::ItemIsSelectable);
    item->setAcceptedMouseButtons(Qt::LeftButton);
    scene.clear();
    scene.addItem(item);

    //if (m_IndexFrame < m_SumFilePath.length()) {
    //    pixmap_sum.load(m_SumFilePath.at(m_IndexFrame));
    //    QGraphicsPixmapItem* item2 = new QGraphicsPixmapItem(pixmap_sum);
    //    item2->setPos(QPointF(0, 0));
    //    item2->setFlag(QGraphicsItem::ItemIsSelectable);
    //    item2->setAcceptedMouseButtons(Qt::LeftButton);
    //    scene2.clear();
    //    scene2.addItem(item2);
    //}
}

